<template>
  <div class="role">
    <a-card :bordered="false">
      <!-- 表格顶部搜索部分 -->
      <c-table-search-form
        v-model="tableSearchForm"
        :datas="tableSearchFormData"
        @onSearch="onSearch"
        @onAdd="onAdd('', 'add')"
      >
        <template slot="allDeleteBtn">
          <a-popconfirm
            :title="`是否确认删除所勾选角色?`"
            v-if="selectedRowKeys.length > 0"
            ok-text="确定"
            cancel-text="取消"
            @confirm="onDeleteAll"
          >
            <a-button icon="delete" type="danger">批量删除</a-button>
          </a-popconfirm>
        </template>
      </c-table-search-form>

      <!-- 表格部分 -->
      <c-table
        rowSelection
        showPagination
        :columns="tableColumns"
        :datas="tableData"
        :loading="loading"
        :paginationDatas="paginationDatas"
        :checkboxProps="checkboxProps"
        @onSelectChange="onSelectChange"
        @onPageSizeChange="onPageSizeChange"
        @onShowNumChange="onShowNumChange"
        :refs="'multipleTable'"
      >
        <!-- 表格自定义部分 -->
        <template slot="companyDirection" slot-scope="row">
          <a-tag v-if="row.tableRow" :color="$dealDic(businessDirection,row.tableRow,'tagColor')">
           {{$dealDic(businessDirection,row.tableRow,'label')}}
          </a-tag>
          <span v-else>-</span>
        </template>

        <!-- 表格操作按钮 -->
        <template slot="action" slot-scope="record">
          <a @click="onView(record.tableRow)"><a-icon type="eye" /> 查看</a>
          <a-divider type="vertical" />
          <a @click="onEdit(record.tableRow)">
            <a-icon type="edit" />编辑
          </a>
          <a-divider type="vertical" />
          <div class="display-inline">
            <a-popconfirm
              ok-text="确定"
              cancel-text="取消"
              @confirm="onDel([record.tableRow.id])"
              v-if="record.tableRow.id >= 10"
            >
              <p slot="title">
                是否确认删除
                <span class="colorMain">{{ record.tableRow.roleName }}</span
                >角色?
              </p>
              <a type="link"> <a-icon type="delete" />删除 </a>
            </a-popconfirm>
            <a v-else  class="textGrey">
              <a-icon type="delete" />删除
            </a>
          </div>
        </template>
      </c-table>

      <!-- 右侧弹窗 -->
      <a-drawer
        :title="handleType == 'add' ? '新增角色' : '编辑角色'"
        :width="'30%'"
        :visible="visible"
        :body-style="{ paddingBottom: '80px' }"
        @close="onCancel"
        :destroyOnClose="true"
      >
        <!-- 弹出窗FormModal自定义 -->
        <c-form-model
          checkStrictly
          @onTreeCheck="onTreeCheck"
          :datas="formData"
          v-model="form"
          :rules="rules"
          ref="formModels"
        >
          <a-input
            slot="roleName"
            allow-clear
            v-model="form.roleName"
            :disabled="formRowDisabled"
          ></a-input>
          <!-- 业务方向 -->
          <a-select
            slot="companyDirection"
            v-model="form.companyDirection"
            :disabled="formRowDisabled"
            @change="getPageResourceList"
          >
            <a-select-option
              v-for="(item, idx) in businessDirection"
              :key="idx"
              :value="item.value"
              >{{ item.label }}</a-select-option
            >
          </a-select>
          
        </c-form-model>
        <div class="drawer-footer-btn flex-center">
          <a-button class="margin-r10" @click="onCancel">取消</a-button>
          <a-button type="primary" :loading="confirmLoading" @click="onOk"
            >确定</a-button
          >
        </div>
      </a-drawer>
    </a-card>
  </div>
</template>

<script>
import {mapActions } from "vuex";
import {
  getTemplateRoles,
  deleteTemplateRole,
  addRoleTemplate,
  getBaseResourceList,
  updateRoleTemplate
} from "@/api/mallSystem/role";
import { refactoringArr, getParent, findChildIdArr } from "@/util/common";
import { businessDirection } from "@/dict/public";

export default {
  name: "Role",
  components: {},
  data() {
    return {
      businessDirection, //业务方向
      checkboxProps: { property: "id", condition: "<", value: "10" },
      formRowDisabled: false,
      handleType: "add",
      deleteIdArr: [],
      selectedRowKeys: [],
      resourceIdsDatas: [],
      selectedRows: [],
      tableSearchForm: {
        searchKey: ""
      },
      tableSearchFormData: [
        {
          label: "请输入角色名称",
          prop: "searchKey",
          type: "search"
        },
        {
          prop: "addBtn",
          type: "addBtn"
        },
        {
          prop: "allDeleteBtn",
          type: "slot"
        }
      ],
      tableColumns: [
        {
          title: "角色名称",
          dataIndex: "roleName",

          align: "center"
        },
        {
          title: "业务方向",
          dataIndex: "companyDirection",
          scopedSlots: { customRender: "companyDirection" },
          align: "center"
        },
        {
          title: "操作",
          key: "action",
          scopedSlots: { customRender: "action" },
          width: 220,
          align: "center"
        }
      ],
      tableData: [],
      loading: false,
      visible: false,
      confirmLoading: false,
      form: {
        roleName: "",
        companyDirection: 1,
        resourceIds: []
      },
      rules: {
        roleName: [
          { required: true, message: "请输入角色名称", trigger: "blur" }
        ],
        companyDirection: [
          { required: true, message: "请输入业务方向", trigger: "change" }
        ]
      },
      paginationDatas: {
        pageSizeOptions: [ "10", "20", "30", "40", "50", "200", "1000" ],
        pageSize: 10,
        pageNum: 1,
        total: 0
      }
    };
  },
  watch: {},
  computed: {
    formData() {
      return [
        {
          label: "角色名称",
          prop: "roleName",
          type: "slot"
        },
        {
          label: "业务方向",
          prop: "companyDirection",
          type: "slot"
        },
        {
          label: "角色权限",
          prop: "resourceIds",
          type: "tree",
          typeData: this.resourceIdsDatas,
          disabled: this.handleType == "view" ? true : false,
          replaceFields: {
            children: "children",
            title: "resourceName",
            key: "id"
          }
        }
      ];
    }
  },
  created() {
    this.onPageOnlod();
    //根据业务方向获取权限资源
    this.getPageResourceList();
  },
  methods: {
  ...mapActions([ "getBaseResourceListByDirection" ]),
    getParent,
    findChildIdArr,
    refactoringArr,
    onTreeCheck(checkedKeys, eventKey, checked) {
      let idArr = [];
      if (checked) {
        checkedKeys.map(id => {
          return getParent(this.resourceIdsDatas, id).map(item => {
            return idArr.push(item.id);
          });
        });
      } else {
        let deleteArr = findChildIdArr(this.resourceIdsDatas, eventKey);
        idArr = checkedKeys;
        idArr = idArr.filter(item => {
          let idList = deleteArr.map(v => v);
          return !idList.includes(item);
        });
      }
      this.$refs.formModels.changeTreeCheck([ ...new Set(idArr) ]);
    },
    renderRowStyle() {
      return {
        style: {
          "text-align": "left"
        }
      };
    },
    onSearch() {
      this.paginationDatas = {
        pageSizeOptions: [ "10", "20", "30", "40", "50", "200", "1000" ],
        pageSize: 10,
        pageNum: 1,
        total: 0
      };
      this.onPageOnlod();
    },
    //新增
    onAdd() {
      this.form = {
        roleName: "",
        companyDirection: 1,
        resourceIds: []
      };
      this.handleType = "add";
      this.visible = true;
    },
    //预览
    onView(row) {
      this.formRowDisabled = true;
      this.handleType = "view";
      this.echoData(row);
    },
    //编辑
    onEdit(row) {
      row.id < 10
        ? (this.formRowDisabled = true)
        : (this.formRowDisabled = false);
      this.handleType = "edit";
      this.echoData(row);
    },
    //数据回显
    echoData(row) {
      this.resourceIdsDatas = []
      for (const key in this.form) {
        if (row[key]) this.form[key] = row[key];
        this.form.id = row.id;
      }
      this.visible = true;
      this.form.resourceIds = row.resources.map(i => i.resourceId);
      this.getPageResourceList();
    },
    getPageResourceList() {
       let parmas = {
        companyDirection: this.form.companyDirection
      }
      this.getBaseResourceListByDirection(parmas).then(res => {
         this.resourceIdsDatas = res
      });
    },
    //初始化页面
    onPageOnlod() {
      this.loading = true;
      getTemplateRoles({
        roleName: this.tableSearchForm.searchKey.trim(),
        pageData: {
          ...{
            pageSize: this.paginationDatas.pageSize,
            pageNum: this.paginationDatas.pageNum
          }
        }
      })
        .then(res => {
          if (!res.data) res.data = {};
          if (!res.data.pageData) res.data.pageData = [];
          this.tableData = res.data.pageData;
          this.paginationDatas.total = res.data.total;
          this.loading = false;
        })
        .finally(() => {
          this.loading = false;
        });
    },
    onDel(idArr) {
      deleteTemplateRole(idArr).then(res => {
        this.$message.success("操作成功");
        this.selectedRowKeys = [];
        this.selectedRows = [];
        this.onPageOnlod();
      });
    },
    onOk() {
      const that = this;
      let onFun;
      that.handleType === "add"
        ? (onFun = addRoleTemplate)
        : (onFun = updateRoleTemplate);
      this.$refs.formModels.handleValidate().then(data => {
        that.confirmLoading = true;
        onFun(data)
          .then(res => {
            that.$message.success("操作成功");
            that.deleteIdArr = [];
            that.selectedRowKeys = [];
            that.selectedRows = [];
            that.onPageOnlod();
            that.confirmLoading = false;
            that.visible = false;
          })
          .catch(() => {
            this.confirmLoading = false;
          });
      });
    },
    onCancel() {
      this.visible = false;
    },
    onDeleteAll() {
      this.deleteIdArr = [];
      this.selectedRowKeys.map(item => {
        return this.deleteIdArr.push(item);
      });
      this.onDel([ ...new Set(this.deleteIdArr) ]);
    },
    onSelectChange(selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys;
      this.selectedRows = selectedRows;
    },
    onShowNumChange(val) {
      this.paginationDatas.pageNum = val;
      this.onPageOnlod();
    },
    onPageSizeChange(val) {
      this.paginationDatas.pageSize = val;
      this.onPageOnlod();
    }
  }
};
</script>
<style lang="less" scoped>
::v-deep td.text-left {
  text-align: left !important;
}
</style>
